﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PIMS.Utils
{
    internal class ComboBoxTools
    {
        /// <summary>
        /// ComboBox文本居中效果
        /// </summary>
        public static void ComboBoxTextCenter(ComboBox comboBox1)
        {
            // 允许代码重新绘制，固定大小
            comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
            comboBox1.DrawItem += ComboBox1_DrawItem;
        }

        private static void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            ComboBox comboBox1 = (ComboBox)sender;
            string s = comboBox1.Items[e.Index].ToString();
            // 计算字符串尺寸（以像素为单位）
            SizeF ss = e.Graphics.MeasureString(s, e.Font);
            // 水平居中
            float left = (float)(e.Bounds.Width - ss.Width) / 2;
            if (left < 0) left = 0f;
            float top = (float)(e.Bounds.Height - ss.Height) / 2;
            // 垂直居中
            if (top < 0) top = 0f;
            top = top + comboBox1.ItemHeight * e.Index;
            // 输出
            e.DrawBackground();
            e.DrawFocusRectangle();
            e.Graphics.DrawString(s, e.Font, new SolidBrush(e.ForeColor), left, top);
        }
    }
}
